// import Io from 'socket.io-client'

class Socket {
  constructor(loginInfo, reconnect_limit) {
    const { username, userid, token } = loginInfo
    this.reconnect_count = 0
    this.reconnect_limit = reconnect_limit || 10
    let url = 'ws://127.0.0.1:3080/'; //172.168.51.200
    // let url = 'ws://139.129.117.239:3080/'; //139.129.117.239 ali
    this.socket = io(url);
    this.username = username;
    this.userid = userid;
    this.socket.emit('add user', loginInfo);
    this.socket.on('disconnect', () => {
      console.log('断网了')
    })
    this.socket.on('reconnect', () => {
      console.log('重连');
      this.socket.emit('add user', loginInfo)
    })
    this.socket.on('reconnect_error', () => {
      console.log('连不上老！')
    })
  }
 
  onLogin (callback) {
    this.socket.on('login', r => {
        callback(r)
    })
  }

  onNotify (callback) {
    this.socket.on('notice', r => {
        callback(r)
    })
  }

  onWarn (callback) {
    this.socket.on('warn', r => {
        callback(r)
    })
  }

  onJoined (callback) {
    this.socket.on('user joined', r => {
        callback(r)
    })
  }

  onFail(callback) {
    this.socket.on('fail login', () => {
      callback()
    })
  }

  onLeft (callback) {
    this.socket.on('user left', r => {
        callback(r)
    })
  }

  onAll(callback) {
    this.socket.on('all user', e => {
      callback(e)
    })
  }

  onMsg (callback) {
    this.socket.on('friend chat', r => {
        callback(r)
    })
  }

  onSend(event, msg) {
    this.socket.emit(event, msg)
  }

  disconnect () {
    this.socket.disconnect(true)
  }

  reconnect () {
    this.socket.on('disconnecting', () => {
      if (this.reconnect_limit > this.reconnect_count) {
        this.reconnect_count += 1
        callback()
      } else {
        console.log('重连失败...')
      }
    });
  }

  onError (callback) {
    this.socket.on('error', () => {
      if (this.reconnect_limit > this.reconnect_count) {
        this.reconnect_count += 1
        callback()
      } else {
        console.log('重连失败...')
      }
    });
  }
}

export default Socket